/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package progin;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 *
 * @author Jiwandono
 */
public class registerServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected String[] processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
String[] a = new String[2];
        for (int i = 0; i < 2; i++) {
            a[i] = null;
        }
        try {
            Class.forName("com.mysql.jdbc.Driver");

            dbConfig dbc = new dbConfig();
            Connection con = DriverManager.getConnection(dbc.url, dbc.username, dbc.password);

                        Statement strx = con.createStatement();
            ResultSet flist2 = strx.executeQuery("SELECT * FROM `prodi`");

            flist2.last();
            if (flist2.getRow() > 0) {
                flist2.first();

                do {
                    a[0] += "<option value=\"" + flist2.getString("idprodi") + "\">" + flist2.getString("nama") + "</option>";

                } while (flist2.next());
            }

                        //add user baru
            if (request.getParameter("login_username") != null) {
                //out.println("au ah");
                Statement str = con.createStatement();
                int pr = str.executeUpdate("INSERT INTO `user` " +
                        "(`username`," +
                        "`password`," +
                        "`fullname`," +
                        "`email`," +
                        "`idprodi`," +
                        "`type`)" +
                        "VALUES ('" + request.getParameter("login_username") + "'," +
                        "MD5('" + request.getParameter("login_password") + "')," +
                        "'" + request.getParameter("login_fullname") + "'," +
                        "'" + request.getParameter("login_email") + "'," +
                        //"'0'," +
                        "'" + request.getParameter("login_prodi") + "'," +
                        "'Mahasiswa')");
                //out.println(str+" ah gelap "+pr);
            

            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery("SELECT * " +
                                           "FROM `user` " +
                                           "WHERE " +
                                           "`username` = '" + request.getParameter("login_username") + "' AND " +
                                           "`password` = MD5('" + request.getParameter("login_password") + "')");

            HttpSession session = request.getSession();
            rs.last();
            if(rs.getRow() == 1) {
                rs.first();

                session.setAttribute("ichat.username", request.getParameter("login_username"));
                session.setAttribute("ichat.usertype", rs.getString("type"));

                response.addCookie(new Cookie("ichat.username", request.getParameter("login_username")));

                if(rs.getString("type").equals("ADMIN")) {
                    response.sendRedirect("adminServlet");
                } else {
                    ServletConfig scfg = getServletConfig();
                    ServletContext sc = scfg.getServletContext();

                    if(sc.getAttribute("ichat.chatdata") == null) {
                        sc.setAttribute("ichat.chatdata", new chatData());

                        /* test */
                        chatData cd = (chatData) sc.getAttribute("ichat.chatdata");
                        cd.addRoom(1, chatRoom.parentType.fakultas, "coba", "jiwo");
                        cd.addRoom(2, chatRoom.parentType.prodi, "wanda", "embuh");
                    }

                    response.sendRedirect("list.jsp");
                }
            } else {
                session.setAttribute("ichat.username", null);
                session.setAttribute("ichat.usertype", null);

                response.sendRedirect("index.jsp?login_attempt=1");
            }

            rs.close();
            st.close();
            con.close();
            }
        } catch(SQLException ex) {
            while (ex != null) {
                out.println ("SQL Exception:  " + ex.getMessage ());
                ex = ex.getNextException ();
            }
        } catch(Exception ex) {
            if(ex != null) {
                out.println ("Exception:  " + ex.getMessage ());
            }
        }

        //out.close();
return a;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
PrintWriter out = response.getWriter();
        String[] adminpage = processRequest(request, response);
        request.setAttribute("user", (adminpage)[0]);

        getServletConfig().getServletContext().getRequestDispatcher("/register.jsp").forward(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
